import { defineConfig, loadEnv } from 'vite'
import { resolve } from 'path'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'
import pxtovw from 'postcss-px-to-viewport'

const loder_pxtovw = pxtovw({
  viewportWidth: 750,
  unitToConvert: 'px',
  viewportUnit: 'rem',
  fontViewportUnit: 'rem',
  selectorBlackList: ['wrap', 'app'],
  exclude: [/node_modules\/vant/i]
})
const vant_pxtovw = pxtovw({
  viewportWidth: 375,
  unitToConvert: 'px',
  viewportUnit: 'rem',
  fontViewportUnit: 'rem',
  selectorBlackList: ['wrap', 'app'],
  exclude: [/^(?!.*node_modules\/vant)/] //忽略除vant之外的
})

export default defineConfig((configEnv) => {
  const config = loadEnv(configEnv.mode, './')
  return {
    plugins: [
      vue(),
      AutoImport({
        // 自动导入vue相关函数
        imports: ['vue'],
        dts: 'src/typings/auto-imports.d.ts',
        eslintrc: {
          // 已存在文件设置默认 false，需要更新时再打开，防止每次更新都重新生成
          enabled: false,
          // 生成文件地址和名称
          filepath: './.eslintrc-auto-import.json',
          globalsPropValue: true
        }
      }),
      Components({
        // 自动导入自定义组件
        dirs: ['src/components'],
        dts: 'src/typings/components.d.ts',
        // 按需引入vant
        resolvers: [VantResolver()]
      })
    ],
    resolve: {
      // 配置别名
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "./src/bem.scss";`
        }
      },
      postcss: {
        plugins: [loder_pxtovw]
      }
    },
    server: {
      port: 3000, // 配置服务器端口
      open: false, // 是否自动打开浏览器
      cors: true // 允许跨域
    }
  }
})
